package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 用户服务
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    //根据用户名查询数据库获取用户信息和关联的角色信息，同时需要查询角色关联的权限信息
    @Override
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);//查询用户基本信息，不包含用户的角色
        if (user == null) {
            return null;
        }
        Integer userId = user.getId();
        //根据用户ID查询对应的角色
        Set<Role> roles = roleDao.findByUserId(userId);
        for (Role role : roles) {
            Integer roleId = role.getId();
            //根据角色ID查询关联的权限
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);
            role.setPermissions(permissions);//让角色关联权限
        }
        user.setRoles(roles);//让用户关联角色
        return user;
    }

    @Override
    public void add(Integer[] roles, User user) {
        //先将user插入user表后会产生id,根据id,将角色遍历并绑定在一起
        String password = user.getPassword();
        //保证也从别的地方跳转过来的安全,对密码进行加密
        if (password!=null){
            user.setPassword(MD5Utils.md5(password));
        }
        userDao.add(user);
        Integer userId = user.getId();
        this.setUserAndRoles(userId, roles);

    }

    @Override//根据用户查询并做分页查询
    public PageResult findPage(QueryPageBean queryPageBean) {
        String queryString = queryPageBean.getQueryString();
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        PageHelper.startPage(currentPage, pageSize);
        Page<User> page = userDao.findQueryString(queryString);
        long total = page.getTotal();
        //当前页的结果
        List<User> result = page.getResult();
        return new PageResult(total, result);
    }

    @Override
    public void edit(Integer[] roles, User user) {
        userDao.edit(user);
        Integer userId = user.getId();
        //并将用户管理绑定的角色全部清空
        userDao.deleteUserAndRoles(user.getId());

        this.setUserAndRoles(userId, roles);

    }

    @Override
    public Map<String, Object> fingById(Integer id) {

        //根据id查询用户基本信息
        User formData = userDao.findById(id);
        //根据角色的全部信息
        List<Role> tableData = roleDao.findAll();
        //根据id 查询中间表的id
        List<Integer> roles = userDao.findUserIdsByRoleId(id);
        Map<String, Object> map = new HashMap<>();
        map.put("formData", formData);
        map.put("roles", roles);
        map.put("tableData", tableData);

        return map;
    }

    @Override
    public void delete(Integer id) {
        //根据id判断有没有关联的中间表
        List<Integer> roles = userDao.findUserIdsByRoleId(id);
        if (roles.size() > 0) {
            throw new RuntimeException("不允许删除,本表关联其他表");

        }else{
            userDao.UserIdsByRoleId(id);
        }
    }


    //将增加绑定数据抽取出来
    private void setUserAndRoles(Integer userId, Integer[] roles) {
        if (userId != null && roles.length > 0) {
            for (Integer role : roles) {
                Map<String, Integer> map = new HashMap<>();
                map.put("userId", userId);
                map.put("roleId", role);
                userDao.setUserIdAndRoleId(map);
            }
        }
    }
}
